package frontend

import (
	"blog/service/data"
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

// 搜索
func SearchHandle(ctx *gin.Context) {
	//页号
	pageId, err := strconv.ParseInt(ctx.Query("page"), 10, 64)
	if err != nil {
		pageId = 1
	}
	if pageId < 1 {
		pageId = 1
	}
	//每一页数据条数
	PageSize := int64(20)
	//关键字
	keyWord := func() string {
		param1 := ctx.Param("keyWord")
		if param1 != "" {
			return param1
		}
		param2 := ctx.Query("keyWord")
		return param2
	}()
	//分类
	typeId := func() int64 {
		param1, _ := strconv.ParseInt(ctx.Param("type"), 10, 64)
		if param1 != 0 {
			return param1
		}
		param2, _ := strconv.ParseInt(ctx.Query("type"), 10, 64)
		return param2
	}()
	//标签
	tagName := func() string {
		param1 := ctx.Param("tagName")
		if param1 != "" {
			return param1
		}
		param2 := ctx.Query("tagName")
		return param2
	}()

	/*
	   url = "/search?page="+destPage;
	   if(keyWord)
	       url+= "&keyWord="+keyWord;
	   if(typeId)
	       url+= "&type="+typeId;
	   if(TagName)
	       url+= "&tagName="+TagName;
	*/

	baseUrl := "/search?"
	if keyWord != "" {
		baseUrl += fmt.Sprintf("&keyWord=%s", keyWord)
	}
	if typeId != 0 {
		baseUrl += fmt.Sprintf("&type=%d", typeId)
	}
	if tagName != "" {
		baseUrl += fmt.Sprintf("&tagName=%s", tagName)
	}

	// 使用数据服务层获取数据
	postService := &data.PostDataService{}
	typeService := &data.TypeDataService{}

	// 暂时使用简单的搜索方法
	resultList, _, _ := postService.SearchPosts(ctx, keyWord, int(pageId), int(PageSize))
	typeInfo, _ := typeService.GetTypeByID(ctx, int(typeId))
	typeList, _ := typeService.GetMainTypes(ctx)

	d := struct {
		KeyWord       string
		ResultList    interface{}
		Page          int
		TypeId        int64
		TypesInfoJson string
		TypeListJson  string
		TagName       string
		BaseUrl       string
	}{
		KeyWord:    keyWord,
		TagName:    tagName,
		ResultList: resultList,
		Page:       int(pageId),
		TypeId:     typeId,
		TypesInfoJson: func() string {
			bytes, _ := json.Marshal(typeInfo)
			return string(bytes)
		}(),
		TypeListJson: func() string {
			bytes, _ := json.Marshal(typeList)
			return string(bytes)
		}(),
		BaseUrl: baseUrl,
	}

	ctx.HTML(http.StatusOK, "search.html", d)
}
